package edu.auctionmart

import org.joda.time.*
import org.jadira.usertype.dateandtime.joda.*

class Auction {

	User winner
	User seller
	Item item
	String auctionTitle
	DateTime startTime
	DateTime endTime
	Float startBid
	Float hiddenMinBid
	Bid currentBid
	String formattedStartTime
	String formattedEndTime
	AuctionStatus status
	
	static beforeInsert = {
	
		String startYear = startTime.getYear()
		String startMonth = startTime.getMonthOfYear()
		String startDate = startTime.getDayOfMonth()
		String startHour = startTime.getHourOfDay()
		String startMinute = startTime.getMinuteOfHour()
		if (startMinute.length() == 1) {
			startMinute = "0" + startMinute
		}
		formattedStartTime = startMonth + "-" + startDate + "-" + startYear + " " + startHour + ":" + startMinute
		
		String endYear = endTime.getYear()
		String endMonth = endTime.getMonthOfYear()
		String endDate = endTime.getDayOfMonth()
		String endHour = endTime.getHourOfDay()
		String endMinute = endTime.getMinuteOfHour()
		if (endMinute.length() == 1) {
			endMinute = "0" + endMinute
		}
		formattedEndTime = endMonth + "-" + endDate + "-" + endYear + " " + endHour + ":" + endMinute
	}

	static constraints = {
		winner(nullable: true)
		seller(nullable: false)
		item(nullable: false)
		bids(nullable: true)
		auctionTitle(nullable: false)
		startTime(nullable: false, validator: {val, obj ->
			if (val > obj.endTime)
				return 'startTimeAfterEndTime.message'
		})
		endTime(nullable: false, validator: {val, obj ->
			if (val < obj.startTime)
				return 'endTimeBeforeStartTime.message'
		})
		startBid(nullable: false)
		hiddenMinBid(nullable: true)
		currentBid(nullable: true, validator: {Bid val, obj ->
			if (val != null && val.getAmount() < obj.startBid)  { return false }
			else return true
		})
		formattedStartTime(nullable: true)
		formattedEndTime(nullable: true)
	}

	static hasMany = [bids: Bid]
	
	static mapping = {
		bids sort: 'amount', order: 'desc'
		sort "endTime"
	}
	
	public float getNextBid() {
		if (currentBid == null) {
			return startBid
		} else {
			return currentBid.getAmount()
		}
	}

	String toString() {
		"${auctionTitle}"
	}
	
}
